package com.password.safe.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.password.safe.constants.Constants;
import com.password.safe.dto.Messages;
import com.password.safe.service.PasswordSafeService;
import com.password.safe.util.InitObservable;
import com.password.safe.util.InitObserver;
import com.password.safe.util.UserCache;

public class InitController extends BaseController implements InitObservable {
	private static Logger logger = Logger.getLogger(InitController.class);
	private List<InitObserver> observers = new ArrayList<InitObserver>();
	private PasswordSafeService passwordSafeService;

	public void addInitObserver(InitObserver observer) {
		this.observers.add(observer);
		
	}
	public void delteInitObserver(InitObserver observer) {
		this.observers.remove(observer);
		
	}
	public void notifyInitSuccess(Messages messages) {
		for (InitObserver o : this.observers) {
			o.initSuccess(messages);
		}
		
	}
	public void notifyInitFailed(Messages messages) {
		for (InitObserver o : this.observers) {
			o.initFailed(messages);
		}
	}
	public void addUser(String username, String password, String repassword) {
		logger.debug("init user...");
		Messages messages = Messages.getInstance();
		if (username.isEmpty()) {
			messages.addMessage(Constants.ERROR_MSG_BLANK_USERNAME, "");
		}
		if (password.isEmpty()) {
			messages.addMessage(Constants.ERROR_MSG_BLANK_NEW_PASSWORD, "");
		}
		if (!password.equals(repassword)) {
			messages.addMessage(Constants.ERROR_MSG_PASSWORD_NOT_EQUAL, "");
		}
		if (!messages.isEmpty()) {
			notifyInitFailed(messages);
			return;
		}
		String temp = username + ":" + password + "\n";
		try {
			this.passwordSafeService.saveText(password, temp);
			notifyInitSuccess(null);
			UserCache.cacheUser(username, password);
		} catch(Exception e) {
			logger.debug(e.getMessage());
			messages.addMessage(Constants.ERROR_MSG_OLD_SAVE_FAILED, e.getMessage());
			notifyInitFailed(messages);
		}
	}
	
	public PasswordSafeService getPasswordSafeService() {
		return passwordSafeService;
	}
	
	public void setPasswordSafeService(PasswordSafeService passwordSafeService) {
		this.passwordSafeService = passwordSafeService;
	}
	
	
}
